from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from apps.goods.models import GoodsCategory, SKU, SPU, SpecificationOption, SPUSpecification, SKUSpecification


# 三级分类序列化器
class SKUCategorieSerializer(ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = "__all__"


# 获取SPU商品规格信息序列化器
class GoodsSimpleSerializer(ModelSerializer):
    class Meta:
        model = SPU
        fields = '__all__'


# 获取SPU商品规格信息序列化器
class GoodsOptionSerializer(ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ('id', 'value',)


class GoodsSpecSerializer(ModelSerializer):
    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()
    # 关联序列化返回 规格选项信息
    options = GoodsOptionSerializer(many=True)  # 使用规格选项序列化器

    class Meta:
        # SPUSpecification中的外键spu关联了spu商品表
        model = SPUSpecification
        fields = "__all__"


# 获取保存SKU数据序列化器
class SKUSpecificationSerializer(ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        # SKUSpecification中sku外键关联了SKU表
        model = SKUSpecification
        fields = ('spec_id', "option_id",)


class SKUSerializers(ModelSerializer):
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()

    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)

    specs = SKUSpecificationSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    def create(self, validated_data):
        # 获取规格信息，并从validated_data数据中，删除规格信息数据
        specs_data = validated_data.pop('specs')
        # 保存sku
        sku = SKU.objects.create(**validated_data)
        # 对规格信息进行遍历，来保存商品规格信息
        for spec_data in specs_data:
            SKUSpecification.objects.create(sku=sku, **spec_data)
            # 返回sku
        return sku

    def update(self, instance, validated_data):
        # 获取规格信息，并从validated——data数据中，删除规格信息数据
        specs_data = validated_data.pop('specs')
        # 调用父类，去实现没有问题的数据更新
        super().update(instance, validated_data)
        # 对规格信息进行遍历，来保存商品规格信息
        for spec_data in specs_data:
            SKUSpecification.objects.filter(sku=instance, spec_id=spec_data.get('spec_id')).update(
                option_id=spec_data.get('option_id'))
            return instance
